package cn.gson.CRM.service.SaleService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.CRM.model.dao.salemanage.PlanDao;
import cn.gson.CRM.model.entity.Plan;
import cn.gson.CRM.model.entity.Plan.State;
import cn.gson.CRM.model.entity.Quotation;
import cn.gson.CRM.model.mapper.PlanMapper;

@Service
public class PlanService
{
	@Autowired
	private PlanDao planDao;
	
	@Autowired
	private QuotationService quoser;
	
	@Autowired
	private ChanceService chanceSer;
	
	@Autowired
	private PlanMapper planmapper;
	
	@Transactional
	public Plan createOpenPlan(Plan plan)
	{
		plan.setState(Plan.State.ING);
		
		Long quoId = quoser.getQuoIdByChanceId(plan.getChance().getId());
		
		if(quoId!=null) {
			plan.setQuotation(new Quotation(quoId));
		}
		Plan save = planDao.save(plan);
		
		chanceSer.updateChancePlan(save.getChance().getId());
		
		
		return save;
		
	}



	public PageInfo<Plan> getPlan(Integer page, Integer rows, Plan search)
	{
		PageHelper.startPage(page, rows);
		
		List<Plan> plans = planmapper.getPlan(search);
		
		PageInfo<Plan> pageInfo = new PageInfo<>(plans);
		
		
		return pageInfo;
	}



	public Plan findOne(Long planid)
	{
		Plan plan = planmapper.getPlan(new Plan(planid)).get(0);
		System.out.println(plan);
		return plan;
	}
	



	public void deletePlan(Long[] planId)
	{
		for (Long long1 : planId)
		{
			Long chanceId = planmapper.getChanceId(long1);
			
			planmapper.updateChancePlan(chanceId);
			planmapper.deletePlanById(long1);
			
		}
		
	}


	@Transactional
	public void finishPlan(Long planId, String state)
	{
		Map<String, Object> param = new HashMap<>();
		
		param.put("planId", planId);
		param.put("state", state);
		
		
		
		planmapper.finishPlan(param);
		
	}



	public void updatePlanQuo(Long chanceid,Long quoId)
	{
		planDao.updatePlanQuo(chanceid,quoId);
		
	}



	public void finishPlanByChance(Long chanceId, State end)
	{
		Map<String, Object> param = new HashMap<>();
		
		param.put("chanceId", chanceId);
		param.put("state", end);
		
		planmapper.finishPlanByChance(param);
		
	}
	
}
